package com.reveregroup.friendconnect;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class FriendConnect {
	private static String siteId;
	
	/**
	 * Initialize the FriendConnect API. Call this method before using any
	 * FriendConnect feature.
	 * 
	 * @param siteId
	 *            - The Site ID for your FriendConnect site. This is listed for
	 *            each of your sites at <a
	 *            href="http://www.google.com/friendconnect"
	 *            >http://www.google.com/friendconnect</a>
	 */
	public static void init(String siteId) {
		if (FriendConnect.siteId != null)
			return;
		
		FriendConnect.siteId = siteId;
		init(FriendConnect.siteId, GWT.getModuleBaseURL());
	}
	
	private native static void init(String siteId, String parentUrl) /*-{
		//initialize API
		$wnd.google.friendconnect.container.setParentUrl(parentUrl); //location of rpc_relay.html and canvas.html
		$wnd.google.friendconnect.container.initOpenSocialApi({
			site: siteId,
			onload: function(securityToken) {
				@com.reveregroup.friendconnect.FriendConnect::userChanged()();
			}
		});
	}-*/;
	
	public native static void requestSignIn() /*-{
		$wnd.google.friendconnect.requestSignIn();
	}-*/;
	
	public native static void requestSignOut() /*-{
		$wnd.google.friendconnect.requestSignOut();
	}-*/;
	
	public native static void isUserLoggedIn(AsyncCallback<Boolean> callback) /*-{
		var req = $wnd.opensocial.newDataRequest();
		  req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
		  req.send(function (data) {
		  	var loggedIn = data.get('viewer').getData() ? true : false;
		  	@com.reveregroup.friendconnect.FriendConnect::isUserLoggedInCallback(Lcom/google/gwt/user/client/rpc/AsyncCallback;Z)(callback,loggedIn);
		  });
	}-*/;
	
	@SuppressWarnings("unused")
	private static void isUserLoggedInCallback(AsyncCallback<Boolean> callback, boolean loggedIn) {
		callback.onSuccess(loggedIn);
	}
	
	public static void addUserChangeHandler(FCUserChangeHandler handler) {
		getHandlerManager().addHandler(FCUserChangeEvent.getType(), handler);
	}
	
	@SuppressWarnings("unused")
	private static void userChanged() {
		handlerManager.fireEvent(new FCUserChangeEvent());
	}
	
	protected static HandlerManager handlerManager;

	protected static HandlerManager getHandlerManager() {
		if (handlerManager == null)
			handlerManager = new HandlerManager(FriendConnect.class);
		return handlerManager;
	}
}
